package top.ywlog.permission.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.ywlog.permission.common.request.PageQuery;
import top.ywlog.permission.common.request.UserParam;
import top.ywlog.permission.common.response.Result;
import top.ywlog.permission.model.Mail;
import top.ywlog.permission.service.MailService;
import top.ywlog.permission.service.SysUserService;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Durian
 * @date: 2020/10/21 20:47
 * @description:
 */
@Slf4j
@Validated
@Controller
@RequestMapping("/sys/user")
public class SysUserController
{
    @Resource
    private SysUserService sysUserService;
    @Resource
    private MailService mailService;

    @PostMapping("/add")
    @ResponseBody
    public Result addUser(@RequestBody @Validated UserParam userParam)
    {
        String password = sysUserService.addUser(userParam);
        sendMail(userParam.getMail(), password);
        return Result.success(password);
    }

    @PutMapping("/update")
    @ResponseBody
    public Result updateUser(@RequestBody @Validated UserParam userParam)
    {
        sysUserService.updateUser(userParam);
        return Result.success();
    }

    @GetMapping("/page/{deptId}")
    @ResponseBody
    public Result page(@PathVariable @NotNull(message = "部门ID不能为空") Integer deptId,
                       @RequestBody @Validated PageQuery pageQuery)
    {
        return Result.success(sysUserService.page(deptId, pageQuery));
    }

    private void sendMail(String email, String password)
    {
        Map<String, Object> attachment = new HashMap<>(1);
        attachment.put("password", password);
        Mail mail = Mail.builder().email(email).title("Test").attachment(attachment).build();
        mailService.sendTemplateMail(mail);
    }
}
